<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 第二版
      // function objectFactory() {
      //   var obj = new Object(),
      //     Constructor = [].shift.call(arguments)

      //   obj.__proto__ = Constructor.prototype

      //   var ret = Constructor.apply(obj, arguments)

      //   return typeof ret === 'object' ? ret||obj : obj
      // }
      //第一个参数为构造函数
      function nnew() {
        let Constructor = Array.prototype.shift.call(arguments)
        let obj = Object.create(Constructor.prototype)
        let ret = Constructor.apply(obj, arguments)
        return typeof ret === 'object' ? ret || obj : obj
      }

      function Otaku(name, age) {
        this.strength = 60
        this.age = age

        return 'handsome boy'
      }

      var person = nnew(Otaku, 'Kevin', '18')

      console.log(person.name) // undefined
      console.log(person.habit) // undefined
      console.log(person.strength) // 60
      console.log(person.age) // 18

      // function Otaku(name, age) {
      //   this.strength = 60
      //   this.age = age

      //   return {
      //     name: name,
      //     habit: 'Games'
      //   }
      // }

      // var person = nnew(Otaku, 'Kevin', '18')

      // console.log(person.name) // Kevin
      // console.log(person.habit) // Games
      // console.log(person.strength) // undefined
      // console.log(person.age) // undefined

      // 第一版
      function Otaku(name, age) {
        this.name = name
        this.age = age

        this.habit = 'Games'
      }

      Otaku.prototype.strength = 60

      Otaku.prototype.sayYourName = function() {
        console.log('I am ' + this.name)
      }

      function objectFactory() {
        let obj = {},
          constructor = Array.prototype.shift.call(arguments)
        obj = Object.create(constructor.prototype)
        constructor.apply(obj, arguments)
        return obj

        // var obj = new Object(),
        //   Constructor = [].shift.call(arguments)
        // obj.__proto__ = Constructor.prototype
        // Constructor.apply(obj, arguments)
        // return obj
      }

      var person = objectFactory(Otaku, 'Kevin', '18')

      console.log(person.name) // Kevin
      console.log(person.habit) // Games
      console.log(person.strength) // 60

      person.sayYourName() // I am Kevin
    </script>
  </body>
</html>
